<?php

declare(strict_types=1);

namespace app\model\system;

use owns\interface\OwnsModelInteface;

class UserModel extends OwnsModelInteface
{
    protected $name = 'system_user';

    protected $field = [];

    /**
     * 查询条件
     * @param object $query
     * @param array $param
     */
    public function scopeCustom(object $query, array $param)
    {
        // 关键词搜索
        if ($keyword = $param['keyword'] ?? '') {
            $query->whereLike('username|phone', '%' . trim($keyword) . '%');
        }
        // 用户名
        if ($username = $param['username'] ?? '') {
            $query->whereLike('username', '%' . trim($username) . '%');
        }
        // 昵称
        if ($nickname = $param['nickname'] ?? '') {
            $query->whereLike('nickname', '%' . trim($nickname) . '%');
        }
        // 电话
        if ($phone = $param['phone'] ?? '') {
            $query->whereLike('phone', '%' . trim($phone) . '%');
        }
        // 邮箱
        if ($email = $param['email'] ?? '') {
            $query->whereLike('email', '%' . trim($email) . '%');
        }
        // 状态
        $status = $param['status'] ?? '';
        if (is_numeric($status)) {
            $query->where('status', '=', $status);
        }
    }

    /*
    * 限制超管账号
    */
    public function scopeUser($query)
    {
        $query->where('id', '>', 1);
    }
    /**
     * 管理员显示字段
     */
    public static function showField(): array
    {
        return [
            'id', 'username', 'nickname', 'phone', 'email', 'avatar', 'signed', 'dashboard',
            'sex', 'role_id', 'group_id', 'remark', 'created_at'
        ];
    }
    /**
     * 角色
     */
    public function role()
    {
        return $this->hasOne(RoleModel::class, 'id', 'role_id')->field('id,name,alias');
    }
    /**
     * 分组
     */
    public function group()
    {
        return $this->hasOne(UserGroupModel::class, 'id', 'group_id')->field('id,name,leader,phone');
    }
}
